//package org.vsoc.modules.license.service.impl;
//
//import cn.hutool.core.lang.UUID;
//import cn.hutool.core.util.ZipUtil;
//import cn.hutool.crypto.asymmetric.KeyType;
//import cn.hutool.crypto.asymmetric.RSA;
//import com.fasterxml.jackson.databind.ObjectMapper;
//import lombok.NonNull;
//import lombok.extern.slf4j.Slf4j;
//import org.apache.commons.codec.binary.Base64;
//import org.apache.commons.compress.utils.FileNameUtils;
//import org.apache.commons.io.FileUtils;
//import org.apache.commons.io.IOUtils;
//import org.apache.commons.lang3.StringUtils;
//import org.jeecg.common.util.CommonUtils;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.core.io.ResourceLoader;
//import org.springframework.stereotype.Service;
//import org.springframework.util.Assert;
//import org.vsoc.license.LicenseCheckModel;
//import org.vsoc.modules.logagent.creator.LicenseCreator;
//import org.vsoc.modules.logagent.creator.LicenseCreatorParam;
//import org.vsoc.modules.logagent.creator.LogAgentLicenseParam;
//import org.vsoc.modules.logagent.service.ILogAgentService;
//
//import javax.annotation.Resource;
//import java.io.File;
//import java.io.FileInputStream;
//import java.io.IOException;
//import java.nio.file.Files;
//import java.nio.file.Path;
//import java.nio.file.Paths;
//import java.util.Arrays;
//import java.util.Objects;
//
//@Slf4j
//@Service
//public class LogAgentServiceImpl implements ILogAgentService {
//    @Resource
//    private ResourceLoader resourceLoader;
//    @Resource
//    private ObjectMapper objectMapper;
//    @Value("${jeecg.path.upload}")
//    private String uploadPath;
//
//    @Value(value = "${jeecg.uploadType}")
//    private String uploadType;
//
//
//    private final String PRIKEY = "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAI54NlsGPFoB/Iy9JATmAtmXgwcQ2d5aD3CY7PKU" +
//            "M3jU6dJZ9UwVxiY9j90LNIHjb1veZfP7eh55DHqqrrP/j5iZTqzpLYJO4mS1kt6EymlMLOrm8TOE8CIxVsPP7OiFoOYqqfRLprmHwW" +
//            "aYbPy7m1gPrV49bEv9oLBSnalJI7UPAgMBAAECgYALp4+BbGX/0kgdIT8y5rgBTHuBAU1j+vJmunPZDOuVrQvVqTCVAUunhti1Hedf" +
//            "4BbqKSwmRIJYaibtr/cWWB0gdiiV57mIuI7eT+N8qqrfLtG4hmps8Reo/1G4P9y0szLJSrdrqaasHD5Cse7DKiea6pSxN2utXPoF4Z" +
//            "KUHy69+QJBAMhnmreAPtuBNfjbFEukALJkIVCseKnYMjNnrZdspJnE3ZaVO+BpndMiIYzBE4quFngdLGO2O7exg3wpB0burYkCQQC1" +
//            "/ifRfFhqt29GqeZXUZkvnXHzJWmE+mAcno9MAmYx7zjKa05qqmW3Ip6DbrzLd6J4M6O08rmxkey0Li7kkX/XAkB+CXKrj7N4l6XbEe" +
//            "WMwONTTlgJhb8Jipff7oelYUWQE9kMuGSE+cexnpidDlz87gnhlu9w8o5SNAkukBssiDWJAkAsz8TsLwryU/KBWspNy9jFQaZSMW8X" +
//            "ADN0OJKeK6UQPJAmP1/SodxjyJFxWW4BR5botAZmQrH4iC7ZetmvDCiHAkAYb2ZuhRbq55K3qB9xENt53fGVuJCO4O/aapUnMdxU91b" +
//            "S7o3QqO9VoOxOckoQDfawRZ8Eovg/xA9DGwn0R46y";
//
//    /**
//     * 根据参数生成logAgent license文件
//     *
//     * @param logAgentLicenseParam 生成证书所需要的参数
//     * @param dfsPathPrefix        证书在DFS中的路径前缀   /tenant/{socTenantId}/logAgent/license/
//     * @return 证书在DFS中的路径
//     */
//    @Override
//    public synchronized String generateLogAgentLicense(@NonNull LogAgentLicenseParam logAgentLicenseParam, String dfsPathPrefix) throws Exception {
//        Assert.noNullElements(Arrays.asList(logAgentLicenseParam, logAgentLicenseParam.getIdentificationCode(),
//                logAgentLicenseParam.getSocTenantId(),
//                logAgentLicenseParam.getIssuedTime(),
//                logAgentLicenseParam.getExpiryTime()), "logAgentLicenseParam is null");
//        LogAgentLicenseParam.AgentInfo agentInfo = logAgentLicenseParam.getAgentInfo();
//        Assert.noNullElements(Arrays.asList(agentInfo, agentInfo.getMachineCode(), agentInfo.getPrivateKey(), agentInfo.getInternetIp(), agentInfo.getInternetSyslogPort()), "logAgentLicenseParam agentInfo param is null");
//        Assert.notNull(uploadPath, "uploadPath is null");
//
//        //标准化本地临时文件夹路径
//        final String LOGAGNET_LICENSE_DIRNAME = "LogAgentLicense";
//        String standardUploadPath = this.uploadPath.replace("\\", File.separator);
//        if (!standardUploadPath.endsWith(File.separator)) {
//            standardUploadPath += File.separator;
//        }
//        standardUploadPath += LOGAGNET_LICENSE_DIRNAME;
//        File uploadPathFile = new File(standardUploadPath);
//        if (!uploadPathFile.exists()) {
//            uploadPathFile.mkdirs();
//        }
//        //生成证书文件
//        File zipLicenseFile = generateZipLicense(logAgentLicenseParam, standardUploadPath);
//        if (Objects.isNull(zipLicenseFile) || !zipLicenseFile.exists()) {
//            throw new Exception("generateLogAgentLicense Exception");
//        }
//        return uploadToDFS(zipLicenseFile, dfsPathPrefix);
//    }
//
//    /**
//     * 生成本地物理文件
//     *
//     * @return
//     */
//    private File generateZipLicense(LogAgentLicenseParam licenseParam, String standardUploadPath) throws IOException {
//        org.springframework.core.io.Resource privateKeyFileResource = resourceLoader.getResource("classpath:/logagent/LogAgentPrivateKey.keystore");
//        org.springframework.core.io.Resource publicCertFileResource2 = resourceLoader.getResource("classpath:/logagent/LogAgentPublicCert.keystore");
//
//        // 生成一个新的临时目录名称
//        Path tempDirPath = Paths.get(System.getProperty("java.io.tmpdir"));
//        String absolutePath = Files.createTempDirectory(tempDirPath, ".temp").toFile().getAbsolutePath();
//        if (!absolutePath.endsWith(File.separator)) {
//            absolutePath = absolutePath + File.separator;
//            log.info("generateZipLicense absolutePath:{}", absolutePath);
//        }
//
//        File privateKeyFile = new File(absolutePath + "LogAgentPrivateKey.keystore");
//        File publicKeyFile = new File(absolutePath + "LogAgentPublicCert.keystore");
//
//        IOUtils.copy(privateKeyFileResource.getInputStream(), Files.newOutputStream(privateKeyFile.toPath()));
//        IOUtils.copy(publicCertFileResource2.getInputStream(), Files.newOutputStream(publicKeyFile.toPath()));
//
//        String licenseDirPath = standardUploadPath + File.separator + UUID.fastUUID().toString().replace("-", "");
//        File licenseDirPathFile = new File(licenseDirPath);
//        if (!licenseDirPathFile.exists()) {
//            boolean mkdirs = licenseDirPathFile.mkdirs();
//            log.debug("mkdir {} result={}", licenseDirPath, mkdirs);
//        }
//        final String LICENSE_FILE_NAME = "LogAgentLicense.lic";
//        final String licenseFile = licenseDirPath + File.separator + LICENSE_FILE_NAME;
//        final String subject = "anxinsiem";
//        LicenseCreatorParam param = new LicenseCreatorParam();
//        param.setSubject(subject);
//        param.setPrivateAlias("LogAgentPrivateKey");
//        param.setKeyPass("F6344MW9OLLMO5AN");
//        param.setStorePass("YCK54392SAUU7SLE");
//
//        param.setLicensePath(licenseFile);
//        param.setPrivateKeysStorePath(privateKeyFile.getAbsolutePath());
//        param.setIssuedTime(licenseParam.getIssuedTime());
//        param.setExpiryTime(licenseParam.getExpiryTime());
//        param.setConsumerType("User");
//        param.setConsumerAmount(1);
//        String infos = objectMapper.writeValueAsString(licenseParam.getAgentInfo());
//        param.setDescription(infos);
//
//        String encodeServerInfo = licenseParam.getIdentificationCode().replaceAll("^BEGIN", "").replaceAll("END$", "");
//        RSA rsaPrikey = new RSA(PRIKEY, null);
//        byte[] decrypt = rsaPrikey.decrypt(Base64.decodeBase64(encodeServerInfo), KeyType.PrivateKey);
//        String serverInfo = new String(decrypt);
//
//        LicenseCheckModel licenseCheckModel = objectMapper.readValue(serverInfo, LicenseCheckModel.class);
//        param.setLicenseCheckModel(licenseCheckModel);
//        LicenseCreator licenseCreator = new LicenseCreator(param);
//        boolean result = licenseCreator.generateLicense();
//        log.info("generateLicense {} result={}", licenseFile, result);
//
//        if (result) {
//            File dstFile = new File(licenseDirPath + File.separator + publicKeyFile.getName());
//            FileUtils.copyFile(publicKeyFile, dstFile);
//            File zip = ZipUtil.zip(licenseDirPath);
//            if (Objects.nonNull(zip)) {
//                log.info("zipLicense {}", zip.getAbsolutePath());
//            } else {
//                log.error("zipLicense error, licenseDirPath={}", licenseDirPath);
//            }
//            FileUtils.deleteDirectory(licenseDirPathFile);
//
//            privateKeyFile.delete();
//            publicKeyFile.delete();
//            return zip;
//        }
//        FileUtils.deleteDirectory(licenseDirPathFile);
//        privateKeyFile.delete();
//        publicKeyFile.delete();
//        return null;
//    }
//
//
//import org.jeecg.common.util.CommonUtils;
//
//import java.io.FileInputStream; /**
//     * 上传文件至文件服务器
//     *
//     * @return
//     */
//    private String uploadToDFS(File zipLicenseFile, String dfsPathPrefix) throws Exception {
//        try (FileInputStream fileInputStream = new FileInputStream(zipLicenseFile)) {
//            String fileName = zipLicenseFile.getName();
//            String licenseFileName = FileNameUtils.getBaseName(fileName) + ".license";
//            String dfsFilePath = dfsPathPrefix.endsWith("/") ? dfsPathPrefix + licenseFileName : dfsPathPrefix + "/" + licenseFileName;
//            String zipLicenseInDFSPath = CommonUtils.upload(fileInputStream, dfsFilePath,uploadType);
//            log.info("upload license to dfs, dfspath={}", zipLicenseInDFSPath);
//            if (StringUtils.isNotBlank(zipLicenseInDFSPath)) {
//                boolean delete = zipLicenseFile.delete();
//                log.info("delete local file {}", zipLicenseFile.getAbsolutePath());
//                return zipLicenseInDFSPath;
//            } else {
//                log.error("upload license to dfs error, dfspath={}", zipLicenseFile.getAbsolutePath());
//                return null;
//            }
//        }
//    }
//}
